import { ref, reactive, computed } from "vue";
import { fabric } from "fabric";
import { Rect, Line, Polygon } from "@/global-utils/fabric";
import { useDeleteModal } from "@/global-hooks/base.hooks";
import type {
  TsG6UseRoleForm,
  CanvasState,
  UseCanvasDraw,
  UseCanvasDrawReturn,
} from "./type";

/** 标准通用化的系统角色表单操作
 * -
 * 只关注左侧 Menu 和 右侧当前已选择 Menu 的 按钮勾选
 * 组件源自于Antd-Design-Vue的 Menu 组件、CheckBox组件
 * @源代码 http://10.168.1.108/r_d_center/common_base_library/web/glasssix-web-vue3-hooks/-/tree/main/packages/src/g6UseRoleForm
 * @返回1
 */
export const g6UseRoleForm = (): TsG6UseRoleForm.HooksReturns => {
  // 参数
  const menuAttr = reactive<TsG6UseRoleForm.MenusAttr>({
    selectedKeys: [],
    openKeys: [],
    menus: [],
    flatMenus: {},
    checkedMenuIds: [],
    checkedBtnIds: [],
  });

  // 整个系统共有多少个菜单id
  const allMenuIds = ref<(string | number)[]>([]);
  // 整个系统共有多少个按钮id
  const allBtnIds = ref<(string | number)[]>([]);

  /** Computed计算属性, 根据 menusConf.selectedKeys 获取当前点击选中的 菜单项
   *
   * 返回: 当前点击选中的 菜单项
   */
  const cSelectedMenu: TsG6UseRoleForm.CSelectedMenu = computed(
    () => menuAttr.flatMenus[menuAttr.selectedKeys[0]]
  );

  /** Computed计算属性, 判断是否存在下级菜单 显示半选和 其余项正常选中状态
   *
   * 返回: 当前点击选中的 菜单项
   */
  const cSelected: TsG6UseRoleForm.CSelected = computed(() => {
    return (btnItem, isChecked) => {
      if (btnItem.ext.buttonType === "entrySubPageBtn") {
        const obj = cSelectedMenu.value.childList.find(
          (item: any) => item.id === btnItem.ext.drillPageId
        );
        const someFlag = obj?.pageBtnList.some((item: any) =>
          menuAttr.checkedBtnIds.includes(item.id)
        );
        const everyFlag = obj?.pageBtnList.every((item: any) =>
          menuAttr.checkedBtnIds.includes(item.id)
        );
        if (isChecked) {
          return everyFlag;
        }
        return everyFlag ? false : someFlag;
      }
      if (isChecked) {
        return menuAttr.checkedBtnIds.includes(btnItem.id);
      }
      return undefined;
    };
  });

  /** Computed计算属性, 根据当前已选择的菜单, 判断 全选和 半选 的状态, 返回 checked = 全选, indeterminate = 半选
   *
   */
  const cMenuCheckBoxState: TsG6UseRoleForm.CMenuCheckBoxState = computed(
    () => {
      if (!menuAttr.selectedKeys.length) {
        return { checked: false, indeterminate: false };
      }
      const curMenu = menuAttr.flatMenus[menuAttr.selectedKeys[0]];
      const isCheckFlas = curMenu.tempAllBtnIds.map((id: string | number) =>
        menuAttr.checkedBtnIds.includes(id)
      );
      // 全选
      const checked: boolean = isCheckFlas.every((flag: boolean) => !!flag);
      // 半选 (如果全选 = true, 那么半选就 = false)
      const indeterminate: boolean = checked
        ? false
        : isCheckFlas.some((flag: boolean) => !!flag);
      return { checked, indeterminate };
    }
  );

  /** 是否禁用 “全选” 按钮
   *
   */
  const cDisableAllCheck: TsG6UseRoleForm.CDisableAllCheck = computed(
    () => allBtnIds.value.length === menuAttr.checkedBtnIds.length
  );

  /** Computed计算属性, 菜单目录和按钮进行勾选操作后, 统计勾选的数量, 需要传参为 菜单的 code值
   *
   * 返回: 字符串值 = 已勾选按钮的数量 / 所有按钮数量
   */
  const cBtnSelectedNums: TsG6UseRoleForm.CBtnSelectedNums = computed(() => {
    return function (id) {
      let data = menuAttr.flatMenus[id];
      const allCounts =
        data.tempAllBtnIds.length - data.soleBrowsePageList.length;
      const checkNumList = menuAttr.flatMenus[id].tempAllBtnIds.filter(
        (id: string | number) => !!menuAttr.checkedBtnIds.includes(id)
      );
      const checkCounts = checkNumList.filter(
        (id: string | number) => !data.soleBrowsePageList.includes(id)
      ).length;
      return `${checkCounts} / ${allCounts}`;
    };
  });

  /** Computed计算属性, 单个按钮的禁用状态判断
   *
   */
  const cDisabledBtnCheck: TsG6UseRoleForm.CDisabledBtnCheck = computed(() => {
    return (btn, menuType) => {
      // 父级页面
      if (menuType === "default-page") {
        if (btn.ext.buttonType === "displayPage") {
          return false;
        }
        // 不存在的话就代表“页面浏览”按钮没有被勾选
        return !menuAttr.checkedBtnIds.includes(btn.displayBtnId);
      }

      // 子级页面
      if (menuType === "drilldown-page") {
        // 按钮是“页面浏览”按钮
        if (btn.ext.buttonType === "displayPage") {
          return true;
        }

        // 当前按钮所属的页面
        const myParent = menuAttr.flatMenus[btn.parentId];
        // 当前按钮所属的上级页面
        const parentMenu = menuAttr.flatMenus[myParent.parentId];

        // 先判断父级的“页面浏览”按钮是否被勾选
        const displayBtn = parentMenu.pageBtnList.find(
          (btn: TsG6UseRoleForm.ButtonItem) =>
            btn.ext.buttonType === "displayPage"
        ) as TsG6UseRoleForm.ButtonItem;
        const displayBtnId = displayBtn.id;
        if (!menuAttr.checkedBtnIds.includes(displayBtnId)) {
          return true;
        }
        // 再判断父级的入口关联按钮是否被勾选
        const parentBtnId = btn.ext.parentBtnId ? btn.ext.parentBtnId : "";
        if (!menuAttr.checkedBtnIds.includes(parentBtnId)) {
          return true;
        }

        // 有多个按钮
        // 最后判断当前按钮所属页面的“页面浏览”按钮是否被勾选
        if (!menuAttr.checkedBtnIds.includes(btn.displayBtnId)) {
          return true;
        }
        return false;
      }
    };
  });

  /** 默认选中第一个菜单页面
   *
   * 参数1: data = 菜单目录数组中的第一项数据
   */
  const setFirstMenu: TsG6UseRoleForm.SetFirstMenu = (data) => {
    if (data.ext.menuType === "default-page") {
      menuAttr.selectedKeys = [data.id];
      return;
    } else if (data.ext.menuType === "directory") {
      if (data.childList.length) {
        setFirstMenu(data.childList[0]);
      }
    }
  };

  /** Menu 组件切换选择
   *
   * 参数1: itemId = 点击的menu节点的id
   */
  const setMenuItemClick: TsG6UseRoleForm.SetMenuItemClick = (itemId) => {
    menuAttr.selectedKeys = [];
    menuAttr.selectedKeys = [itemId];
  };

  /** 格式化后端接口返回的菜单数据, 并赋值给 menuAttr.menus 和 menuAttr.flatMenus, 并且默认选中第一个菜单
   *
   * 参数1: resMenus = 要格式化的菜单数据(数组)
   */
  const setFormatMenus: TsG6UseRoleForm.SetFormatMenus = (resDatas) => {
    let tempObj: Record<string | number, string | number> = {};
    const loopFn = (treeList: TsG6UseRoleForm.MenuItem[]): void => {
      treeList.forEach((menu: TsG6UseRoleForm.MenuItem) => {
        allMenuIds.value.push(menu.id);
        menu.childList = Array.isArray(menu.childList) ? menu.childList : [];
        menu.pageBtnList = Array.isArray(menu.pageBtnList)
          ? menu.pageBtnList
          : [];
        menu.tempAllBtnIds = [];
        menu.soleBrowsePageList = []; //子页面中仅有一个页面浏览按钮的数组
        tempObj[menu.id] = "";

        // 判断并格式化 menu.ext
        menu.ext =
          typeof menu.ext === "string" && menu.ext !== "{}"
            ? JSON.parse(menu.ext)
            : {};
        // 判断并格式化 menu 每个按钮数据的 ext
        menu.pageBtnList.forEach((btn: TsG6UseRoleForm.ButtonItem) => {
          btn.ext =
            typeof btn.ext === "string" && btn.ext !== "{}"
              ? JSON.parse(btn.ext)
              : {};
          allBtnIds.value.push(btn.id);
          menu.tempAllBtnIds.push(btn.id);

          // 临时的数据处理, 后期删除此段代码
          // if (Reflect.has(btn.ext, 'btnType')) {
          // 	if (btn.ext.btnType === 'displayPage') {
          // 		btn.ext.buttonType = 'displayPage';
          // 	}

          // 	if (btn.ext.btnType === 'normal') {
          // 		btn.ext.buttonType = 'normalBtn';
          // 	}
          // 	if (btn.ext.btnType === 'entrySubPage') {
          // 		btn.ext.buttonType = 'entrySubPageBtn';
          // 	}

          // 	if (btn.ext.btnType === 'normal' && menu.ext.menuType === 'drilldown-page') {
          // 		btn.ext.buttonType = 'subPageNormalBtn';
          // 	}
          // }

          if (btn.ext.buttonType === "displayPage") {
            tempObj[btn.parentId] = btn.id;
          } else {
            btn.displayBtnId = tempObj[btn.parentId];
          }
        });
        // 如果 menu 属于目录类型的话, 则将其 id 添加到 menusConf.openKeys 中
        menu.ext.menuType === "directory" && menuAttr.openKeys.push(menu.id);
        // 子级递归遍历
        if (menu.childList.length) {
          // 计算子页面仅有页面浏览按钮的数量id
          menu.childList.forEach((item: any) => {
            if (
              item.pageBtnList.length === 1 &&
              item.pageBtnList[0].code === "look-page"
            ) {
              menu.soleBrowsePageList.push(item.pageBtnList[0].id);
            }
          });

          loopFn(menu.childList);
        }

        // 有多个子标签页的下级页面, 将相同标签的按钮按顺序放在一起, 判断词 = ext.hasMoreTabs
        if (menu.ext.menuType === "drilldown-page" && menu.ext.hasMoreTabs) {
          const sortBtns = [];
          const dataInfo: Record<any, any> = {};
          menu.pageBtnList.forEach((btn: TsG6UseRoleForm.ButtonItem) => {
            if (btn.ext.buttonType === "displayPage") {
              sortBtns.unshift(btn);
            } else {
              if (!dataInfo[btn.ext.tabSort as number]) {
                dataInfo[btn.ext.tabSort as number] = [];
              }
              dataInfo[btn.ext.tabSort as number].push(btn);
            }
          });
          for (const key in dataInfo) {
            sortBtns.push(...dataInfo[key]);
          }
          menu.pageBtnList = sortBtns;
        }

        menu.childList.forEach((sub: TsG6UseRoleForm.MenuItem) => {
          sub.pageBtnList.forEach((btn: TsG6UseRoleForm.ButtonItem) => {
            menu.tempAllBtnIds.push(btn.id);
          });
        });
        // 扁平化赋值
        menuAttr.flatMenus[menu.id] = menu;
      });
    };
    loopFn(resDatas);
    menuAttr.menus = [...resDatas];
    tempObj = {};
    setFirstMenu(menuAttr.menus[0]);
  };

  /** 根据后端接口返回的已选择id, 更新 menuAttr.checkedMenuIds 和 menuAttr.checkedBtnIds
   * 参数1: selectedIds 后端接口返回的已选id集合
   */
  const setSelectedIds: TsG6UseRoleForm.SetSelectedIds = (selectedIds) => {
    menuAttr.checkedMenuIds = allMenuIds.value.filter(
      (id: string | number) => !!selectedIds.includes(id)
    );
    menuAttr.checkedBtnIds = allBtnIds.value.filter(
      (id: string | number) => !!selectedIds.includes(id)
    );
  };

  /** 全选 或者 取消全选 的功能
   *
   * @param check = 全选？取消全选
   */
  const setCheckAllMenus: TsG6UseRoleForm.SetCheckAllMenus = (check) => {
    menuAttr.checkedMenuIds = check ? [...allMenuIds.value] : [];
    menuAttr.checkedBtnIds = check ? [...allBtnIds.value] : [];
  };

  const findMenuIsCheck = (): void => {
    Object.keys(menuAttr.flatMenus).forEach((key: string | number) => {
      const item = menuAttr.flatMenus[key];
      const flag = item.tempAllBtnIds.some(
        (id: string | number) => !!menuAttr.checkedBtnIds.includes(id)
      );

      if (flag) {
        if (item.pageBtnList && item.pageBtnList.length) {
          const displayPageId = item.pageBtnList.find(
            (item: any) => item.ext.buttonType === "displayPage"
          ).id;
          displayPageId && menuAttr.checkedBtnIds.push(displayPageId);
        }

        menuAttr.checkedMenuIds.push(item.id);
      } else {
        menuAttr.checkedMenuIds = menuAttr.checkedMenuIds.filter(
          (id: string | number) => id !== item.id
        );
      }
    });
    menuAttr.checkedMenuIds = [...new Set(menuAttr.checkedMenuIds)];
  };

  /** 已选择菜单目录的整体勾选
   *
   * 参数: check = 是否勾选
   */
  const setMenuItemCheck: TsG6UseRoleForm.SetMenuItemCheck = (check) => {
    if (!menuAttr.selectedKeys.length) {
      return;
    }
    const cId = menuAttr.selectedKeys[0];
    const btnIds = menuAttr.flatMenus[cId].tempAllBtnIds;
    if (check) {
      menuAttr.checkedBtnIds.push(...btnIds);
    } else {
      menuAttr.checkedBtnIds = menuAttr.checkedBtnIds.filter(
        (id: string | number) => !btnIds.includes(id)
      );
    }
    // 按钮所属的menu更新勾选情况
    findMenuIsCheck();
  };

  /** 单个按钮的勾选操作
   *
   * 参数1: check = 是否勾选
   * 参数2: btn = 当前操作的按钮
   */
  const setButtonItemCheck = (
    check: boolean,
    btn: TsG6UseRoleForm.ButtonItem
  ): void => {
    // 所属菜单
    const myMenu: TsG6UseRoleForm.MenuItem = menuAttr.flatMenus[btn.parentId];
    // 勾选
    if (check) {
      menuAttr.checkedBtnIds.push(btn.id);

      // 当前按钮所属的菜单是父级菜单, myMenu.ext.menuType = 'default-page'
      if (myMenu.ext.menuType === "default-page") {
        // 当按钮的ext.buttonType = 'entrySubPageBtn'
        if (btn.ext.buttonType === "entrySubPageBtn") {
          const drilldownMenu =
            menuAttr.flatMenus[btn.ext.drillPageId as string | number];
          menuAttr.checkedBtnIds.push(...drilldownMenu.tempAllBtnIds);
        }
      }

      // 当前按钮所属的菜单是子级菜单, myMenu.ext.menuType = 'drilldown-page'
      // 暂无
    }

    // 不勾选
    if (!check) {
      menuAttr.checkedBtnIds = menuAttr.checkedBtnIds.filter(
        (id: string | number) => id !== btn.id
      );
      // 当前按钮所属的菜单是父级菜单, myMenu.ext.menuType = 'default-page'
      if (
        myMenu.ext.menuType === "default-page" ||
        myMenu.ext.menuType === "drilldown-page"
      ) {
        // 当按钮的ext.buttonType = 'displayPage', 取消勾选当前菜单的其他按钮(包含子级页面的所有按钮)
        if (btn.ext.buttonType === "displayPage") {
          menuAttr.checkedBtnIds = menuAttr.checkedBtnIds.filter(
            (id: string | number) => !myMenu.tempAllBtnIds.includes(id)
          );
        }
        // 当按钮的ext.buttonType = 'entrySubPageBtn', 取消勾选按钮关联的子级页面的所有按钮
        if (btn.ext.buttonType === "entrySubPageBtn") {
          const drilldownMenu =
            menuAttr.flatMenus[btn.ext.drillPageId as string | number];
          menuAttr.checkedBtnIds = menuAttr.checkedBtnIds.filter(
            (id: string | number) => !drilldownMenu.tempAllBtnIds.includes(id)
          );
        }
      }

      // 当前按钮所属的菜单是子级菜单, myMenu.ext.menuType = 'drilldown-page'
      // 暂无
    }

    menuAttr.checkedBtnIds = [...new Set(menuAttr.checkedBtnIds)];
    // 按钮所属的menu更新勾选情况
    findMenuIsCheck();
  };

  return {
    /**
     * 参数&属性
     */
    menuAttr,

    /** Computed计算属性, 根据 menusConf.selectedKeys 获取当前点击选中的 菜单项
     *
     * 返回: 当前点击选中的 菜单项
     */
    cSelectedMenu,

    /** Computed计算属性, 根据当前已选择的菜单, 判断 全选和 半选 的状态, 返回 checked = 全选, indeterminate = 半选
     */
    cMenuCheckBoxState,

    /** 是否禁用 “全选” 按钮
     */
    cDisableAllCheck,

    /** Computed计算属性, 菜单目录和按钮进行勾选操作后, 统计勾选的数量, 需要传参为 菜单的 code值
     *
     * 返回: 字符串值 = 已勾选按钮的数量 / 所有按钮数量
     */
    cBtnSelectedNums,

    /** Computed计算属性, 单个按钮的禁用状态判断
     */
    cDisabledBtnCheck,

    /** Menu 组件切换选择
     *
     * 参数1: menuItem = 点击的menu节点
     */
    setMenuItemClick,

    /** 格式化后端接口返回的菜单数据, 并赋值给 menuAttr.menus 和 menuAttr.flatMenus, 并且默认选中第一个菜单
     *
     * 参数1: resMenus = 要格式化的菜单数据(数组)
     */
    setFormatMenus,

    /** 根据后端接口返回的已选择id, 更新 menuAttr.checkedMenuIds 和 menuAttr.checkedBtnIds
     *
     * 参数1: selectedIds 后端接口返回的已选id集合
     */
    setSelectedIds,

    /** 全选 或者 取消全选 的功能
     *
     * 参数: check = 全选？取消全选
     */
    setCheckAllMenus,

    /** 已选择菜单目录的整体勾选
     *
     * 参数: check = 是否勾选
     */
    setMenuItemCheck,

    /** 单个按钮的勾选操作
     *
     * 参数1: check = 是否勾选
     *
     * 参数2: btn = 当前操作的按钮
     */
    setButtonItemCheck,

    cSelected,
  };
};

/**
 * 标注绘制 hooks
 * @returns
 */
export const useCanvasDraw: UseCanvasDraw = () => {
  // 画布状态变量
  const canvasState = reactive<CanvasState>({
    canvas: null, // 画布canvas
    video: null, //视频dom
    rect: null,
    line: null,
    polygon: null,
    backgroundVideo: null,
    scale: 1,
    isClearnCanvas: false, //清除画布
    isClearnOk: false, //清除画布
    drawType: 1, //绘制类型
    isEditCavans: false, //是否修改了画布
    selectGraph: null,
  });
  const { setOpenDeleteModal } = useDeleteModal();

  //静态配置
  const staticOptions = {
    nowGraphFillColor: "rgba(245, 151, 0, 0.3)", // 填充色
    nowGraphStrokeColor: "#FFDB93", // 边框色
    backgroundColor: "#010A17", // 背景色
    // cornerColor:'#FFDB93'	// 控制点色
  };

  // 获取容器宽度
  const getCanvasWidth = (): number => {
    const canvasWidth = document.querySelector(".draw-container")?.clientWidth;
    return canvasWidth || 0;
  };
  // 获取容器高度
  const getCanvasHeight = (): number => {
    const canvasHeight =
      document.querySelector(".draw-container")?.clientHeight;
    return canvasHeight || 0;
  };

  // 初始化画布
  const initCanvas: UseCanvasDrawReturn["initCanvas"] = async () => {
    try {
      // 初始化canvas
      canvasState.canvas = new fabric.Canvas("canvas");

      // 禁止选中
      canvasState.canvas.selection = false;
      // 读取视频宽高
      canvasState.canvas.setWidth(getCanvasWidth());
      canvasState.canvas.setHeight(getCanvasHeight());
      canvasState.canvas.backgroundColor = staticOptions.backgroundColor;
      // 矩形
      canvasState.rect = new Rect(canvasState.canvas);
      // 线
      canvasState.line = new Line(canvasState.canvas, { objectCaching: false });
      // 多边形
      canvasState.polygon = new Polygon(canvasState.canvas, {
        objectCaching: false,
      });

      // 监听canvas操作 验证是否有修改
      canvasState.canvas.on("mouse:up", () => {
        canvasState.isEditCavans = true;
        canvasState.selectGraph = canvasState.canvas?.getActiveObject();
      });

      canvasState.canvas.on("selection:created", (event: any) => {
        let selectedObject = (event?.selected as any)[0];
        canvasState.selectGraph = selectedObject;
      });
      // 监听鼠标双击

      // canvasState.canvas.on('mouse:down', () => {});
    } catch (error) {
      console.error(error);
    }
  };

  // 绘制视频
  const animationId = ref(); //requestAnimationFrame定时器id 用于页面卸载
  const drawVideo: UseCanvasDrawReturn["drawVideo"] = () => {
    canvasState.backgroundVideo = new fabric.Image(
      canvasState.video as HTMLVideoElement
    );
    canvasState.backgroundVideo.scale(canvasState.scale);
    if (canvasState.backgroundVideo) {
      canvasState.canvas?.setBackgroundImage(
        canvasState.backgroundVideo,
        canvasState.canvas.renderAll.bind(canvasState.canvas),
        {
          left: 0,
          top: 0,
        }
      );
      // 设置居中
      canvasState.canvas?.centerObject(canvasState.backgroundVideo);
      canvasState.canvas?.renderAll();
      animationId.value = requestAnimationFrame(drawVideo);
    } else {
      // 去掉背景
      canvasState.canvas?.setBackgroundImage(
        "",
        canvasState.canvas?.renderAll.bind(canvasState.canvas)
      );
    }
  };
  // 停止绘制
  const stopDraw: UseCanvasDrawReturn["stopDraw"] = () => {
    canvasState.polygon?.endDraw();
    canvasState.line?.endDraw();
  };

  // 清除当前正在绘制的对象
  const clearCurrentObject = async (): Promise<void> => {
    canvasState.polygon?.clearCurrentObject();
    canvasState.line?.clearCurrentObject();
  };

  // 启用画布上的所有对象
  const enableAllObject = (): void => {
    canvasState.canvas?.getObjects().forEach((item: any) => {
      item.set({
        evented: true,
        selectable: true,
      });
    });
  };

  // 绘制矩形
  const drawPolygon: UseCanvasDrawReturn["drawPolygon"] = () => {
    stopDraw();
    enableAllObject();
    canvasState.polygon?.startDraw();
  };

  // 绘制直线
  const drawLine: UseCanvasDrawReturn["drawLine"] = () => {
    stopDraw();
    enableAllObject();
    canvasState.line?.startDraw();
  };

  // 删除当前选中的图形
  const delGraph: UseCanvasDrawReturn["delGraph"] = () => {
    canvasState.isEditCavans = true;
    canvasState.canvas?.remove(canvasState.selectGraph);
    canvasState.selectGraph = null;
  };
  // 清空画布
  const clearCanvas: UseCanvasDrawReturn["clearCanvas"] = async () => {
    canvasState.canvas?.getObjects().forEach(function (obj: any) {
      if (obj !== canvasState.canvas?.backgroundImage) {
        canvasState.canvas?.remove(obj);
      }
    });
    canvasState.canvas?.renderAll();
  };
  // 销毁
  const destroy: UseCanvasDrawReturn["destroy"] = async () => {
    canvasState.rect?.destroy();
    canvasState.line?.destroy();
    canvasState.polygon?.destroy();
    canvasState.canvas = null;
  };
  // 清屏
  const handleClearCanvas: UseCanvasDrawReturn["handleClearCanvas"] = () => {
    const clearCanvasInfo = {
      title: "确认要清空绘制区域吗？",
      okText: "确认",
      centered: true,
      cancelText: "取消",
    };
    const clearFun = async (): Promise<void> => {
      await clearCurrentObject();
      await clearCanvas();
      canvasState.isClearnCanvas = true;
      canvasState.isClearnOk = true;
      canvasState.isEditCavans = true;
    };

    setOpenDeleteModal(clearFun, clearCanvasInfo, () => {
      // 清屏调用接口成功后,isClearnCanvas = true
      // 这时候关闭弹窗会进行判断, 如果 isClearnCanvas = true， 不进行操作

      if (!canvasState.isClearnOk) {
        canvasState.isClearnCanvas = false;
      }
    });
  };

  // 绘制默认区域
  const drawDefaultArea: UseCanvasDrawReturn["drawDefaultArea"] = (
    axisList
  ) => {
    if (!canvasState.canvas?.backgroundImage) {
      return;
    }
    axisList.forEach((item) => {
      if (canvasState.drawType === 1 || canvasState.drawType === 3) {
        const position = canvasState.polygon?.getCurrentAxis(
          {
            top: canvasState.backgroundVideo?.top as number,
            left: canvasState.backgroundVideo?.left as number,
          },
          item,
          canvasState.scale
        );
        const newPolygon = canvasState.polygon?.create(
          position as fabric.Point[],
          {
            selectable: false,
            evented: false,
          }
        );
        canvasState.canvas?.add(newPolygon as fabric.Polygon);

        drawPolygon();
      } else if (canvasState.drawType === 2) {
        const position = canvasState.line?.getCurrentAxis(
          {
            top: canvasState.backgroundVideo?.top as number,
            left: canvasState.backgroundVideo?.left as number,
          },
          item,
          canvasState.scale
        );
        const lineObj = canvasState.line?.create(position, {
          selectable: false,
          evented: false,
        });
        canvasState.canvas?.add(lineObj as fabric.Line);
        drawLine();
      }
    });
  };
  // 绘制整个区域
  const fullRect: UseCanvasDrawReturn["fullRect"] = () => {
    if (!canvasState.canvas?.backgroundImage) {
      return;
    }
    try {
      stopDraw();
      const bgcObj = canvasState.canvas.backgroundImage as fabric.Image;
      const width = (bgcObj.width as number) * (bgcObj.scaleX || 0);
      const height = (bgcObj.height as number) * (bgcObj.scaleY || 0);
      const left = bgcObj.left || 0;
      const top = bgcObj.top || 0;
      const fullRect = canvasState.rect?.create({
        width: width,
        height: height,
        left: left,
        top: top,
        fill: staticOptions.nowGraphFillColor,
        stroke: staticOptions.nowGraphStrokeColor,
        strokeWidth: 1,
      });
      canvasState.canvas.add(fullRect as fabric.Rect);
      // 只读
      fullRect?.set({
        selectable: false,
        evented: false,
      });
    } catch (error) {
      console.error(error);
    }
  };

  //获取坐标值
  const customizeDrawAreaCoordinatesList = ref<number[][]>(); // 坐标数组
  const getCoordinateValue: UseCanvasDrawReturn["getCoordinateValue"] = () => {
    const newArr: number[][] = [];
    canvasState.canvas?.getObjects().forEach((item: any) => {
      if (item instanceof fabric.Polygon) {
        // 获取坐标
        const axis = canvasState.polygon?.getOriginAxis(
          {
            top: canvasState.backgroundVideo?.top as number,
            left: canvasState.backgroundVideo?.left as number,
          },
          item,
          canvasState.scale
        );
        newArr.push(axis as unknown as number[]);
      } else if (item instanceof fabric.Line) {
        const axis = canvasState.line?.getOriginAxis(
          {
            top: canvasState.backgroundVideo?.top as number,
            left: canvasState.backgroundVideo?.left as number,
          },
          item,
          canvasState.scale
        );
        newArr.push(axis as unknown as number[]);
      }
    });
    console.log(newArr, "newArr");

    customizeDrawAreaCoordinatesList.value = newArr;
    return newArr;
  };

  // 监听键盘delete按键
  document.addEventListener("keydown", (e) => {
    if (e.key === "Delete") {
      // 删除激活的矩形
      const activeObject = canvasState.canvas?.getActiveObject();
      if (activeObject) {
        canvasState.canvas?.remove(activeObject);
        canvasState.canvas?.renderAll();
      }
    }
  });

  onUnmounted(() => {
    cancelAnimationFrame(animationId.value);
    canvasState.polygon?.destroy();
  });

  return {
    initCanvas,
    drawVideo,
    handleClearCanvas,
    drawDefaultArea,
    clearCanvas,
    fullRect,
    stopDraw,
    drawLine,
    drawPolygon,
    destroy,
    getCoordinateValue,
    delGraph,
    canvasState,
    customizeDrawAreaCoordinatesList,
  };
};
